package com.jw.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IpUtil {

	// 获取网页源码
	public static String httpGet(String url) {

		StringBuffer buffer = new StringBuffer();

		try {
			URLConnection conn = new URL(url).openConnection();
			conn.addRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100");
			// 设置超时时间
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);

			InputStream inputStream = conn.getInputStream();
			InputStreamReader streamReader = new InputStreamReader(inputStream, "GB2312");
			BufferedReader reader = new BufferedReader(streamReader);

			String line = null;

			while ((line = reader.readLine()) != null) {
				buffer.append(line).append(System.lineSeparator());
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return buffer.toString();
	}

	/**
	 * 通过正则表达式获取网站的ip
	 * 
	 * @param url
	 * @param reg
	 * @return
	 */
	public static String getIP(String url, String reg) {
		String html = httpGet(url);
		// 提出IP
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(html);
		if (matcher.find()) {
			String ip = matcher.group(1);
			return ip;
		}
		return null;
	}

	/**
	 * 根据已知dns获取自己的ip,可以是tplink或者花生壳的
	 * 
	 * @return
	 */
	public static String getIpByDomain(String myDns) {
		try {
			InetAddress address = InetAddress.getByName(myDns);
			return address.getHostAddress();
		} catch (UnknownHostException uhe) {
			uhe.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		System.out.println(getIpByDomain(""));
	}



}
